package com.swsc.ai.service.impl;

import com.swsc.ai.entity.AiObtainDataEntity;
import com.swsc.ai.enums.CommonResultCode;
import com.swsc.ai.mapper.AiObtainDataMapper;
import com.swsc.ai.configs.FtpConfiguration;
import com.swsc.ai.entity.request.FtpReqParam;
import com.swsc.ai.service.FtpDownloadFileService;
import com.swsc.ai.utils.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * @describe: ftp文件下载实现类
 * @author: 容若
 * @created: 2024-06-20 10:14
 */
@Slf4j
@Service("ftpDownloadFileServiceImpl")
public class FtpDownloadFileServiceImpl implements FtpDownloadFileService {
    /**
     * hdfs服务器路径
     */
    @Value("${hdfs.path}")
    String hdfsPath;
    @Value("${hdfs.user}")
    String hadoopUser;
    @Autowired
    private FtpConfiguration ftpConfiguration;
    @Autowired
    private FtpUtil ftpUtil;
    @Autowired
    private AiObtainDataMapper obtainDataMapper;
    @Override
    public String downloadFtpFile(FtpReqParam reqParam) {
        /**
         * 判断请求是否重复
         */
        int total = obtainDataMapper.isRepeatRequest(reqParam.getReqToken());
        if (total != 0) {
            return CommonResultCode.REPEAT_REQ.getMsg();
        }
        AiObtainDataEntity aiObtainDataEntity = new AiObtainDataEntity(
                reqParam.getReqToken(),
                0,
                new Date(),
                new Date(),
                reqParam.getFileFullName().split("[.]")[0],
                reqParam.getFtpPath() + "/" + reqParam.getFileFullName(),
                reqParam.getPartition(),
                reqParam.getTradeDate(),
                "ftp download",
                "ftp文件下载"
        );
        int insertNum = obtainDataMapper.insert(aiObtainDataEntity);
        if (insertNum == 0) {
            return CommonResultCode.DB_FAIL.getMsg();
        }
        log.info("开始连接ftp服务器：{}{}{}", ftpConfiguration.ftpSourceProperties().getHost(), ":", ftpConfiguration.ftpSourceProperties().getPort());
        try {
            String localStr = startDownloadFtpFileToLocal(reqParam);
            String hdfsStr = startDownloadFtpFileToHDFS(reqParam);
            return localStr + "\n" + hdfsStr;
        } catch (IOException e) {
            log.info("下载ftp文件发生异常：{}", e.toString());
            return CommonResultCode.DOWNLOAD_FAIL.getMsg();
        }
    }

    /**
     * 开始下载ftp文件，保存到hdfs
     * @param reqParam ftp信息
     */
    private String startDownloadFtpFileToHDFS(FtpReqParam reqParam) throws IOException {
        startBuildFtpConnect();
        log.info("文件夹是否存在：{}", ftpUtil.existFile(reqParam.getFtpPath()));
        if (!ftpUtil.existFile(reqParam.getFtpPath())) {
            return "ftp文件不存在";
        }
        /**
         * 拼接hdfs文件路径
         */
        StringBuffer stringBuffer = new StringBuffer(ftpConfiguration.ftpSourceProperties().getSaveFileHdfsPath());
        stringBuffer.append("/").append(reqParam.getTradeDate()).append("/");
        stringBuffer.append(reqParam.getFileFullName().split("[.]")[0]).append("/");
        stringBuffer.append(reqParam.getFileFullName());
        String remoteFilePath = reqParam.getFtpPath() + "/" + reqParam.getFileFullName();
        return ftpUtil.downloadFileToHDFS(remoteFilePath, stringBuffer.toString(), hdfsPath, hadoopUser);
    }

    /**
     * 开始下载ftp文件，保存到本地磁盘
     * @param reqParam ftp信息
     */
    private String startDownloadFtpFileToLocal(FtpReqParam reqParam) throws IOException {
        startBuildFtpConnect();
        log.info("文件夹是否存在：{}", ftpUtil.existFile(reqParam.getFtpPath()));
        if (!ftpUtil.existFile(reqParam.getFtpPath())) {
            return "ftp文件不存在";
        }
        String localPath = ftpConfiguration.ftpSourceProperties().getSaveFileLocalPath() + "/" + reqParam.getFileFullName();
        return ftpUtil.downloadFileToLocal(reqParam.getFtpPath() + "/" + reqParam.getFileFullName(), localPath);
    }

    /**
     * 开始建立ftp连接
     * @throws IOException
     */
    private void startBuildFtpConnect() throws IOException {
        ftpUtil.connect(ftpConfiguration.ftpSourceProperties().getHost(),
                ftpConfiguration.ftpSourceProperties().getPort(),
                ftpConfiguration.ftpSourceProperties().getUsername(),
                ftpConfiguration.ftpSourceProperties().getPassword());
    }
}
